package com.ml.view;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by xpf on 2017/6/3 :)
 * 检测APP页面是否一直运行,不运行就直接启动
 */

public class MyService extends Service {

    private final static String TAG = "MyService";
    public static final String CANCEL_MONITOR = "cancelMonitor";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (CANCEL_MONITOR.equals(intent.getAction())) {
                Log.e(TAG, "onReceive:kill app process！");
                killMyselfPid(); // 杀死自己的进程
            }
        }
    };

    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            checkIsAlive();
        }
    };

    /**
     * 检测应用是否活着
     */
    private void checkIsAlive() {
        if (_ischeking) {
            return;
        }
        _ischeking = true;
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA).format(new Date());
        Log.e("colin83","CustodyService Run: " + format + "---" + time);

        String pName = "com.ml.view";
        int uid = getPackageUid(getApplicationContext(), pName);
        if (uid > 0) {
            boolean rstA = isAppRunning(getApplicationContext(), pName);
//            boolean rstB = isProcessRunning(getApplicationContext(), uid);
            if (rstA) {
                //指定包名的程序正在运行中
                Log.e("colin83","App is running...");
            } else {
                //指定包名的程序未在运行中
                Log.e("colin83","App is not running, restart app...");
//                Intent intent = new Intent();
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setClass(MyService.this, WelcomeActivity.class);
//                startActivity(intent);
                Intent intent = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//与正常页面跳转一样可传递序列化数据,在Launch页面内获得
//                intent.putExtra("REBOOT","reboot");
                startActivity(intent);

//                android.os.Process.killProcess(android.os.Process.myPid());
            }
        } else {
            //应用未安装
            Log.e(TAG, "App is not installed.");
        }

        _ischeking = false;

    }

    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;

    @Override
    public void onCreate() {
        super.onCreate();

        if (Build.VERSION.SDK_INT >= 26) {
            setForeground();
        } else {
            startForeground(PID, new Notification());
        }

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time++;
                    mHandler.sendEmptyMessage(CHECKAPP);
                }
            }
        }.start();
    }

    private static final String ID = "channel_1";
    private static final String NAME = "前台服务";
    private final int PID = android.os.Process.myPid();

    @TargetApi(26)
    private void setForeground() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(ID, NAME, NotificationManager.IMPORTANCE_HIGH);
        manager.createNotificationChannel(channel);
        Notification notification = new Notification.Builder(this, ID)
                .setContentTitle("欢迎使用esm") //欢迎使用vn84app
                .setContentText("")
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(true)
//                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .build();
        startForeground(PID, notification);

        //消除通知 无效
//        if (null == mConnection) {
//            mConnection = new AssistServiceConnection();
//        }
//        this.bindService(new Intent(this, AssistService.class), mConnection, Service.BIND_AUTO_CREATE);
    }


    int time = 0;
    boolean _ischeking = false;

    public static final int CHECKAPP = 1313;//检查APP

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (CHECKAPP == msg.what) {
                checkIsAlive();
            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /**
     * 杀死自身的进程
     */
    private void killMyselfPid() {
        int pid = android.os.Process.myPid();
        String command = "kill -9 " + pid;
        Log.e(TAG, "killMyselfPid: " + command);
        stopService(new Intent(MyService.this, MyService.class));
        try {
            Runtime.getRuntime().exec(command);
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     * Created by cafeting on 2017/2/4.
     *
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    //获取已安装应用的 uid，-1 表示未安装此应用或程序异常
    public static int getPackageUid(Context context, String packageName) {
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(packageName, 0);
            if (applicationInfo != null) {
                Log.d(TAG, "app uid:" + applicationInfo.uid);
                return applicationInfo.uid;
            }
        } catch (Exception e) {
            return -1;
        }
        return -1;
    }

    /**
     * 判断某一 uid 的程序是否有正在运行的进程，即是否存活
     * Created by cafeting on 2017/2/4.
     *
     * @param context 上下文
     * @param uid     已安装应用的 uid
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isProcessRunning(Context context, int uid) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am.getRunningServices(200);
        if (runningServiceInfos.size() > 0) {
            for (ActivityManager.RunningServiceInfo appProcess : runningServiceInfos) {
                if (uid == appProcess.uid) {
                    return true;
                }
            }
        }
        return false;
    }
}
